package connection;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
//a.k.a. HibernateSessionManager
public class Connector {
	private static SessionFactory hbSessionFactory = null;
	public static Session session = null;
	private static ThreadLocal<Session> hbThreadLocal = new ThreadLocal<Session>();

	// Extended by all DAO objects
	public Connector() {
		startNewSession();
	}

	// Starts a new session and opens a new transaction.
	public static void startNewSession() {
		Configuration cfg = new Configuration();
		cfg.configure();
		hbSessionFactory = cfg.buildSessionFactory();
		session = hbSessionFactory.openSession();
		hbThreadLocal.set(session);
		session.beginTransaction();
	}

	// Called when transaction need to be commited. Opens a new transaction
	// immediately after that
	public static void commitTransaction() {
		if (session.getTransaction().isActive()) {
			session.flush();
			session.getTransaction().commit();
			session.beginTransaction();
		}
	}

	// Called when exception is thrown and the transaction need to be
	// rollbacked. Creates a new session immediately after that because the old
	// one is in inconsistent state.
	public static void rollbackTransaction() {
		if (session.getTransaction().isActive()) {
			session.getTransaction().rollback();
			startNewSession();
		}
	}

	public static SessionFactory getHbSessionFactory() {
		return hbSessionFactory;
	}

	public static void setHbSessionFactory(SessionFactory hbSessionFactory) {
		Connector.hbSessionFactory = hbSessionFactory;
	}

	public static Session getSession() {
		return hbThreadLocal.get();
	}

	public static void setSession(Session session) {
		hbThreadLocal.set(session);
	}

	public static ThreadLocal<Session> getHbThreadLocal() {
		return hbThreadLocal;
	}

	public static void setHbThreadLocal(ThreadLocal<Session> hbThreadLocal) {
		Connector.hbThreadLocal = hbThreadLocal;
	}
}
